package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.common.SHA1Util;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")//给接口加前缀
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    //查询所有数据
    @GetMapping
    public Result findAll(){
        List<User> all=userMapper.findAll();
        return Result.success(all);
    }
    //登陆
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String username=user.getUname();
        String password=user.getPwd();

        User encryptedUser = new User();
        encryptedUser.setUname(username);
        encryptedUser.setPwd(SHA1Util.generateSHA1(password));

        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        User user1=userService.login(encryptedUser);
        return Result.success(user1);
    }
    //注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        String username=user.getUname();
        String password=user.getPwd();

        User encryptedUser = new User();
        encryptedUser.setUname(username);
        encryptedUser.setPwd(SHA1Util.generateSHA1(password));

        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.register(encryptedUser));
    }
    //新增或更新
    @PostMapping
    public Result save(@RequestBody User user){//requestbody把前台传来的json转化为java对象
        return Result.success(userService.saveUser(user));
    }
    //改密码
    @PostMapping("/updatepwd")
    public Result updatePwd(@RequestBody User user){
        User encryptedUser = new User();
        encryptedUser.setUname(user.getUname());
        encryptedUser.setPwd(SHA1Util.generateSHA1(user.getPwd()));
        return Result.success(userMapper.updatePwd(encryptedUser));
    }
    //删除
    @DeleteMapping("/{uname}")
    public Result delete(@PathVariable String uname){
        return Result.success(userMapper.deleteByUname(uname));
    }
    //查找用户
    @GetMapping("/findbyname")
    public Result findByUname(@RequestParam String uname){//get用requestparam,post用requestbody
        List<User> one=userMapper.findByUname(uname);
        return Result.success(one);
    }

}
